package y_ut.dbtools.imp;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.log4j.Logger;

import au.com.bytecode.opencsv.CSVReader;

/**
 * 
 * @author youxz
 *
 */
public class ExpCsvZipReader implements IImpReader {

	private Logger logger = Logger.getLogger(ExpCsvZipReader.class);
	private String path;
	
	private ZipFile zipFile;
	
	private String []currentColNames;
	
	private Enumeration<ZipEntry> entries;
	
	private CSVReader reader;

	

	public ExpCsvZipReader(String path) {
		super();
		this.path = path;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean open() {
		try {
			zipFile = new ZipFile(new File(path));
			
			entries =  (Enumeration<ZipEntry>) zipFile.entries();
			
		} catch (Exception e) {
			logger.info(e);
			e.printStackTrace();
		} 
		
		return true;
	}
	
	@Override
	public String[] getColNames() {
		return currentColNames;
	}

	@Override
	public boolean hasNextTable() {
		return entries.hasMoreElements();
	}

	@Override
	public String nextTable() {
		try{
			ZipEntry entry = entries.nextElement();
			String tableName = entry.getName();
			InputStream is = zipFile.getInputStream(entry);
			
			reader = new CSVReader(new InputStreamReader(is));
			 currentColNames = reader.readNext();
			
			 return tableName.substring(0,tableName.length()-4);
		}catch(Exception e){
			logger.error(e);
			e.printStackTrace();
		}
		return null;
	}


	@Override
	public String[] getNextRowData() {
		// TODO Auto-generated method stub
		try {
			return  reader.readNext();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public boolean close() {
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	

}
